const Base = require('./base.js');
const crypto = require("crypto");
const rp = require('request-promise');
module.exports = class extends Base {
    async showSettingsAction() {
        let info = await this.model('show_settings').where({
            id: 1
        }).find();
        return this.success(info);
    }
    async parsePhoneAction() {
      let code = this.post('code');
      let iv = this.post('iv');
      let encryptedData = this.post('encryptedData');
      // console.log(token,'token',iv,encryptedData)
      const options = {
        method: 'GET',
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        qs: {
          grant_type: 'authorization_code',
          js_code: code,
          secret: think.config('weixin.secret'),
          appid: think.config('weixin.appid')
        }
      };
      let sessionData = await rp(options);
      sessionData = JSON.parse(sessionData);
      console.log(sessionData,'sessionData',typeof sessionData)
      const WeixinSerivce = this.service('weixin', 'api');
      const weixinPhoneInfo = await WeixinSerivce.decryptUserInfoData(sessionData.session_key, encryptedData, iv);
      console.log(weixinPhoneInfo,'weixinPhoneInfo')
      
      let data = {
          mobile: weixinPhoneInfo.phoneNumber,
          name_mobile: 1
      };
      let info = await this.model('user').where({
          id: think.userId
      }).update(data);
      console.log(info,'wxuser')
      return this.success(info)
    }
    async saveAction() {
        let name = this.post('name');
        // let mobile = this.post('mobile');
        // var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(16[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
        // if (mobile.length < 11) {
        //     return this.fail(200, '长度不对');
        // } else if (!myreg.test(mobile)) {
        //     return this.fail(300, '手机不对哦');
        // }
        // if (name == '' || mobile == '') {
        //     return this.fail(100, '不能为空')
        // }
        let data = {
            name: name
        };
        let info = await this.model('user').where({
            id: think.userId
        }).update(data);
        return this.success(info);
    }
    async userDetailAction() {
        let info = await this.model('user').where({
            id: think.userId
        }).field('mobile,name').find();
        return this.success(info);
    }
};